//
//  WPTabbar.m
//  Weibo
//
//  Created by wpapple on 16/5/30.
//  Copyright © 2016年 wpapple. All rights reserved.
//

#import "WPTabbar.h"
#import "ComposedViewController.h"

@interface WPTabbar ()

@property (nonatomic,weak) UIButton * btn;

@end

@implementation WPTabbar

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
         [self setaddButton];
    }
    return self;
}

- (void)awakeFromNib{
    NSLog(@"");
    int i = 0;
    for (UIView *childview in self.subviews) {
        if ([childview isKindOfClass:[UIControl class]] && ![childview isKindOfClass:[UIButton class]]) {
            childview.tag = i;
            i++;
        }
    }
}

-(void)setaddButton
{
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [btn setImage:[UIImage imageNamed:@"tabbar_compose_icon_add"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"tabbar_compose_icon_add_highlighted"] forState:UIControlStateHighlighted];
    
    [btn setBackgroundImage:[UIImage imageNamed:@"tabbar_compose_button"] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"tabbar_compose_button_highlighted"] forState:UIControlStateHighlighted];
    
    self.btn = btn;
    
    [self addSubview:btn];
    
    [btn addTarget:self action:@selector(compose:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)compose:(UIButton *)sender
{
    UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Composed" bundle:nil];
    
    UINavigationController *nav = [sb instantiateInitialViewController];

    [vc presentViewController:nav animated:YES completion:^{
        
    }];
    
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
    int index = 0;
    
    CGFloat tabbarW = self.bounds.size.width / 5.0;
    CGFloat tabbarH = self.bounds.size.height;
    
    for (int i = 0; i <self.subviews.count; i++) {
        UIView *childview = self.subviews[i];
        
        if ([childview isKindOfClass:[UIControl class]] && ![childview isKindOfClass:[UIButton class]]) {
            
            if (index == 2) {
                index ++;
            }
            CGFloat tabbarX = index * tabbarW;
            
            childview.frame = CGRectMake(tabbarX, 0, tabbarW, tabbarH);
            
            index++ ;
        }
    }
    
    self.btn.size = self.btn.currentBackgroundImage.size;
    self.btn.center = CGPointMake(self.width * 0.5, self.height *0.5);
    
}
@end
